//
//  TMThemeManager.swift
//  ThemeManagement
//
//  Created by fanxiaoxin_1987@126.com on 06/20/2022.
//  Copyright (c) 2022 fanxiaoxin_1987@126.com. All rights reserved.
//

import UIKit

open class TMThemeManager {
    public static let shared = TMThemeManager(userDefaultsKey: "@ThemeManagement-Default-Theme")
    let userDefaultsKey: String
    /// 当前主题
    open var current: TMTheme {
        didSet {
            if self.current != oldValue {
                self.update()
                UserDefaults.standard.setValue(self.current.rawValue, forKey: self.userDefaultsKey)
            }
        }
    }
    /// 所有待变更的对象都存在此处
    private var targetObservers: [TMTargetObserver] = []
    /// 所有待变更的对象都存在此处
    private var blockObservers: [TMBlockObserver] = []
    
    private init(userDefaultsKey: String) {
        self.userDefaultsKey = userDefaultsKey
        if let current = UserDefaults.standard.string(forKey: userDefaultsKey) {
            self.current = .init(rawValue: current)
        } else {
            self.current = .default
        }
    }
    /// 设置默认值
    public func setDefault(_ theme: TMTheme) {
        if UserDefaults.standard.string(forKey: userDefaultsKey) == nil {
            self.current = theme
        }
    }
    
    /// 更新主题
    func update() {
        self.targetObservers.forEach { $0.doAction() }
        self.blockObservers.forEach { $0.doAction() }
    }
    ///添加主题变更监听
    @discardableResult
    public func addObserve<T>(_ observer: T, for action: @escaping (T) -> Void) -> TMTargetObserver where T : AnyObject {
        self.targetObservers.removeAll(where: { $0.observer == nil })
        let ob:TMTargetObserver
        if let o = self.targetObservers.first(where: { $0.observer === observer }) {
            ob = o
        }else{
            ob = TMTargetObserver(observer)
            self.targetObservers.append(ob)
        }
        ob.actions.append { (object) in
            action(object as! T)
        }
        return ob
    }
    ///添加主题变更监听
    @discardableResult
    public func addObserve(_ block: @escaping () -> Void) -> TMBlockObserver {
        let ob = TMBlockObserver(block)
        self.blockObservers.append(ob)
        return ob
    }
}

extension TMValue {
    /// 获取当前主题对应的值
    public func value() -> Value? {
        return self.value(for: TMThemeManager.shared.current)
    }
}

public protocol TMValueType {
    
}
extension UIColor: TMValueType {}
extension UIImage: TMValueType {}
extension UIFont: TMValueType {}
extension String: TMValueType {}
extension UIStatusBarStyle: TMValueType {}

extension TMValueType {
    /// 获取当前主题对应的样式
    public static func theme(_ value: TMValue<Self>) -> Self? {
        return value.value()
    }
}

public protocol TMObjectType { }
extension NSObject: TMObjectType { }

extension TMObjectType where Self: AnyObject {
    /// 可设置跟随主题变化的样式
    public var theme: TMValueSetter<Self> {
        return TMValueSetter(object: self)
    }
}
